import { DownOutlined, PlusOutlined, PaperClipOutlined } from '@ant-design/icons';
import { Modal, Divider, Form, Space, message, TreeSelect } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { QueryFilter, ProFormText,ProFormSelect,ProFormDatePicker } from '@ant-design/pro-form';
import { queryDeviceTypeList} from '@/services/devicetype';
import { queryAreaTree } from '@/services/area';
import { queryDeviceList } from '@/services/device';
import styles from '../index.less';

const FormItem = Form.Item;


export interface SelectTableProps {
  modalVisible: boolean;
  onSubmit: (ids: string,names:string,type?:number) => void;
  onCancel: () => void;
  deviceList?:API.DeviceItem[];
  selectedids?:number[];
  deviceType?:number;
  selectionType?:string;
}






const SelectDeviceModal: React.FC<SelectTableProps> = (props) => {
  const { modalVisible, onSubmit: handleAdd, onCancel,selectedids,selectionType='checkbox',deviceType} = props;
  const actionRef = useRef<ActionType>();

  const [selectedRowKeys,setSelectedRowKeys] = useState<number[]>(selectedids||[]);
  const [selectedRows,setSelectedRows] = useState<API.DeviceItem[]>([]);
  const [typeId, setTypeId] = useState<number>();
  const [areaTreeData, setAreaTreeData] = useState<API.TreeNodeItem[]>([]);
  const [typeSelectValues, setTypeSelectValues] = useState([]);
  const [typeEnumValues, setTypeEnumValues] = useState({});
  const [areaEnumValues, setAreaEnumValues] = useState({});
  const [dataSource, setDataSource] = useState(props.deviceList);
console.log(dataSource)

  const okHandle = async () => {
    if(selectedRowKeys.length==0){
      message.error({
        content: '请选择设备',
        className: 'custom-class',
        style: {
          marginTop: '20vh',
        },
      });
      return ;
    }
      const idstr=selectedRowKeys.join(',');
      var names="";
      selectedRows.forEach(function(val, index, arr){
        names+=","+val.deviceName;
      });
      names=names.substring(1);
      handleAdd(idstr,names,typeId);

  
  };

  const onSelectChange = async (sKeys,sRows ) => {
    setSelectedRowKeys(sKeys);
    setSelectedRows(sRows)
  };

  const columns: ProColumns[] = [

    {
      title: '区域',
      dataIndex: 'areaId',
      valueEnum: areaEnumValues,
    },    
    {
      title: '设备类型',
      dataIndex: 'deviceTypeId',
      valueEnum:typeEnumValues,
      initialValue:deviceType==null?null:deviceType.toString(),


    },    
    {
      title: '设备编号',
      dataIndex: 'deviceNo',
      search:false,
 
    },
    {
      title: '设备名称',
      dataIndex: 'deviceName',
    },  {
      title: '设备品牌',
      dataIndex: 'deviceBrand',
      search:false,
    },
    {
      title: '设备型号',
      dataIndex: 'deviceModel',
      search:false,
 
    }
  ];


  useEffect(() => {
    const setSelectData = async () => {
      const deviceType = await queryDeviceTypeList();
      let tsdata = [];
      let tdata = {};
      if (deviceType && deviceType.length > 0) {
        deviceType.forEach(item => {
          tsdata.push({ label: item.typeName, value: item.typeId })
          tdata[item.typeId] = { text: item.typeName };
        });
      }
      setTypeEnumValues(tdata);
      setTypeSelectValues(tsdata);
      let trees = await queryAreaTree();
      let ddata = {};
      if (trees && trees.length > 0) {
        trees.forEach(item => {
          ddata[item.key] = { text: item.title };
          if (item.children != null) {
            item.children.forEach(children => {
              ddata[children.key] = { text: children.title };
            })
          }
        });
      }
      setAreaEnumValues(ddata);
      setAreaTreeData(trees);
     
      
    };
    setSelectData();


  }, []);
  return (
    <Modal
    width={820}
    // destroyOnClose
    title="请选择设备"
    visible={modalVisible}
    onOk={okHandle}
    onCancel={() => onCancel()}
    
    className={styles.selectTable}
  >
         <div style={{ padding: '20px 26px' }}>
        <QueryFilter defaultCollapsed labelWidth={'auto'} onReset ={()=> {
           setDataSource(props.deviceList);
        }} onFinish={async (values: any) => {
          console.log(values)
          setDataSource(await queryDeviceList({...values,useState:1}));
           }}>
           
             <Form.Item name={"areaId"} label={"所在区域"} >
             <TreeSelect 
            style={{ width: '100%' }}
            dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
            treeData={areaTreeData}
            placeholder="请选择所在区域"
            treeDefaultExpandAll
          /></Form.Item>
          <ProFormSelect name="deviceTypeId"  label="设备类型" options={typeSelectValues} />
          <ProFormText name="deviceName" label="设备名称" />

        </QueryFilter>
      
      </div> 
      <ProTable
        headerTitle=""
        actionRef={actionRef}
        rowKey="deviceId"
       
        options={false}
        search={false}
        tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 项
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消选择
              </a>
            </span>
          </Space>
        )}
       
        rowSelection={{    selectedRowKeys,onChange: onSelectChange,type: selectionType}}
       dataSource={dataSource}
      //  request={ async ( param) => {
      //    console.log(param)
      //  // return  await  queryDevice({ ...param ,...{deviceTypeId:deviceType}})  }}
      //   return  await  queryDevice({ ...param,...{useState:1}})  }}
        columns={columns}
        pagination={{
          defaultCurrent: 1,
          defaultPageSize: 10,
        }}
      />
   </Modal>
  );
};

export default SelectDeviceModal;
